<template>
  <div class="content-box">
    <!--标题-->
    <div class="content-title">
      <i class="el-icon-search"></i>
      <span>高级查询</span>
    </div>
    <el-form label-width="120px" style="width:100%">
      <div class="content-item-box">
        <!--已保存规则-->
        <div class="title-box">
          <div class="item-title">已保存规则</div>
          <div>
            <span class="himt"></span>
            <el-tooltip content="通过【保存规则】后系统将记录配置信息，方便下次使用" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </div>
        </div>
        <div class="contents">
          <el-row class="item-row">
            <el-col :span="24">
              <div v-if="savedRuleConfigs==null || savedRuleConfigs.length<=0" style="text-align: center;font-size: 14px;">暂无保存规则</div>
              <el-table v-else
                        :height="maxHeight"
                        :data="savedRuleConfigs"
                        border
                        style="width: 100%"
                        :show-header="false"
                        @row-click="handleRuleClick">
                <el-table-column show-overflow-tooltip  type="index" width="30"/>
                <el-table-column
                  prop="ruleName"
                  label="规则名称">
                </el-table-column>
                <el-table-column
                  prop="createTime"
                  label="添加时间"
                  width="155">
                </el-table-column>
                <el-table-column show-overflow-tooltip label="操作"
                                 width="50"
                                 align="center"
                                 fixed="right" >
                  <template slot-scope="scope">
                    <i class="el-icon-delete del-column" @click="removeSetInfo(scope.row)"></i>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </div>


        <!--条件配置-->
        <div class="title-box">
          <div class="item-title">规则配置</div>
          <div>
            <span class="himt">添加多个规则实现组合查询</span>
            <el-tooltip content="点击【添加规则】可实现多个条件进行组合查询；【清空规则】将清空当前规则配置中的信息" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </div>
        </div>
        <div class="contents">
          <div :style="{height:maxHeight+'px',overflow:'auto'}">
            <el-row class="item-row item-row-content" v-for="(rules,index) in ruleConfigs" :key="index">
              <el-col :span="1" class="item-row-box">
                <span class="rule-number">{{index+1}}</span>
              </el-col>
              <el-col :span="7" class="item-row-box">
                <!--字段信息-->
                <el-select filterable clearable
                           v-model="rules.column"
                           @change="(val) => columnChange(val, index)">
                  <el-option v-for="(column,index) in fieldInfo" :key="index"
                             v-if="column.isQuery == '1'"
                             :label="column.columnComment"
                             :value="column.columnName"/>
                </el-select>
              </el-col>
              <el-col :span="5" class="item-row-box" v-if="rules.formType != 'datetime' && rules.formType != 'date'">
                <!--查询方式-->
                <el-select v-model="rules.queryType" @change="(val) => handleChangeQueryType(val,index)">
                  <el-option label="包含" value="LIKE" />
                  <el-option label="等于" value="EQ" />
                  <el-option label="不等于" value="NE" />
                  <el-option label="大于" value="GT" />
                  <el-option label="大于等于" value="GTE" />
                  <el-option label="小于" value="LT" />
                  <el-option label="小于等于" value="LTE" />
                  <el-option label="为空" value="NULL" />
                  <el-option label="不为空" value="NOTNULL" />
                </el-select>
              </el-col>
              <!--过滤值-->
              <el-col v-if="rules.queryType != 'NULL' && rules.queryType != 'NOTNULL'"
                      :span="rules.formType != 'datetime' && rules.formType != 'date'?9:14" class="item-row-box">
                <!-- 日期时间组件 -->
                <el-date-picker v-if="rules.formType == 'datetime' || rules.formType == 'date'"
                                clearable size="small"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                format="yyyy-MM-dd HH:mm:ss" v-model="rules.queryVal" type="datetimerange" range-separator="-"
                                start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00','23:59:59']">
                </el-date-picker>
                <!-- 下拉选择组件 -->
                <el-select v-else-if="rules.formType == 'select' || rules.formType == 'checkbox' || rules.formType == 'radio'|| rules.formType == 'multipleSelect'"
                           v-model="rules.queryVal" multiple placeholder="请选择过滤值">
                  <el-option v-for="(dict,index) in formDataOptions[rules.column]" :key="index" :label="dict.dictLabel" :value="dict.dictValue"/>
                </el-select>
                <!-- 文本录入组件 -->
                <el-input v-else clearable placeholder="请录入过滤值"  v-model="rules.queryVal"/>
              </el-col>
              <!--删除选项-->
              <el-col :span="2" class="item-row-box">
                <i class="el-icon-delete del-column" @click="delRuleItem(index)"></i>
              </el-col>
            </el-row>
          </div>
          <div style="margin: 15px 0;display: flex;justify-content: space-between;">
            <el-button
              style="padding-bottom: 0"
              icon="el-icon-circle-plus-outline"
              type="text"
              @click="addRuleItem">
              添加规则
            </el-button>
            <el-button
              style="padding-bottom: 0;color: red"
              icon="el-icon-remove-outline"
              type="text"
              @click="resetRules">
              清空规则
            </el-button>
          </div>
        </div>

        <!--组合规则-->
        <div class="title-box">
          <div class="item-title">组合规则</div>
          <div>
            <span class="himt"></span>
            <el-tooltip content="【符合全部】以上所有条件都满足的数据；【符合任一】以上条件只要满足其中任意一个条件的数据" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </div>
        </div>
        <div class="contents">
          <div class="rule-type-box">
            <div>
              <el-radio v-model="ruleType" label="AND">符合全部</el-radio>
              <el-radio v-model="ruleType" label="OR">符合任一</el-radio>
            </div>
            <el-button type="primary" plain @click="save">保存规则</el-button>
          </div>
        </div>

        <div class="contents">
          <el-row class="item-row">
            <el-col :span="24">
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="close">取消</el-button>
            </el-col>
          </el-row>
        </div>

      </div>

    </el-form>

  </div>
</template>
<script>
import request from "@/utils/request";
import {GotoYsdMixins} from "@/views/youshuda/utils/GotoYsdMixins";

export default {
  name: "SuperQuery",
  mixins:[GotoYsdMixins],
  components: {
    EditDisplay: () => import('@/views/youshuda/components/FormEdit/display')
  },
  props: {
    //业务模块配置信息
    tabGenId: {
      default: ''
    },
    //对象中下拉框
    formDataOptions: {},
    //表单字段信息
    fieldInfo: {
      type: Array,
      default:()=>[]
    }
  },
  computed:{
    /** 最大高度 **/
    maxHeight(){
      return this.appMain.height/4;
    }
  },
  data() {
    return {
      //选择类型组件
      ChooseType: ["select", "radio","checkbox"],
      //规则ID
      ruleId:'',
      //规则名称
      ruleName:'',
      //规则配置信息
      ruleConfigs:[],
      //规则类型  符合任一：OR    符合全部：AND
      ruleType:'AND',
      //已保存的规则配置信息
      savedRuleConfigs:[]
    };
  },
  created() {
    /** 初始化 **/
    this.init();
    /** 获取配置信息 **/
    this.getSetInfo();
  },
  methods: {
    /** 初始化 **/
    init(){
      if(this.ruleConfigs.length<=0){
        /** 重置查询规则 **/
        this.resetRules();
      }
    },
    /** 重置查询规则 **/
    resetRules(){
      //规则ID
      this.ruleId = '';
      //规则名称
      this.ruleName = '';
      //规则配置信息
      this.ruleConfigs = [];
      //规则类型  符合任一：OR    符合全部：AND
      this.ruleType = 'AND'
      /** 添加查询规则 **/
      this.addRuleItem();
    },
    /** 添加查询规则 **/
    addRuleItem(){
      this.ruleConfigs.push({
        'column':'',
        'queryType':'LIKE',
        'formType':'',
        'queryVal':''
      })
    },
    /** 删除规则 **/
    delRuleItem(index){
      if(index>-1 && index< this.ruleConfigs.length){
        this.ruleConfigs.splice(index,1)
      }
    },
    /** 查询数据 **/
    handleQuery(){
      /** 校验规则是否为空 **/
      let rules = [];
      for(let i=0;i<this.ruleConfigs.length;i++){
        let item = {...this.ruleConfigs[i]}
        if(this.strIsEmpty(item.column)){
          continue;
        }
        /** 判断查询方式 **/
        if(!['NULL','NOTNULL'].includes(item.queryType) && this.strIsEmpty(item.queryVal)){
          this.msgError("请维护，第【"+(i+1)+"】项规则过滤值");
          return false;
        }
        /** 判断是否为多选的情况 **/
        if(['select','checkbox','multipleSelect'].includes(item.formType)){
          let queryVal = item.queryVal
          if(queryVal && Array.isArray(queryVal)){
            item.queryVal = queryVal.join(',')
          }
        }
        /** 日期时间 **/
        if(['datetime','date'].includes(item.formType)){
          let queryVal = item.queryVal
          if(queryVal && Array.isArray(queryVal)){
            item.queryVal = queryVal[0] + ' TO '+ queryVal[1]
          }
        }
        rules.push(item)
      }
      let queryInfo = null
      if(rules && rules.length>0){
        queryInfo = JSON.stringify({
          ruleType:this.ruleType,
          ruleConfigs: rules
        })
      }
      this.$emit("handleQuery", queryInfo)
    },
    /** 字段切换，获取对应类型信息 **/
    columnChange(val, index){
      let columnInfo = this.fieldInfo.find(item => item.columnName === val)
      this.ruleConfigs[index]['formType']=columnInfo.htmlType
      if(columnInfo.htmlType == 'datetime' || columnInfo.htmlType == 'date'){
        this.ruleConfigs[index]['queryType']= ''
      }
    },
    /** 查询方式切换，处理对应类型信息 **/
    handleChangeQueryType(val,index){
      if(val === 'NULL' || val === 'NOTNULL'){
        this.ruleConfigs[index]['queryVal']= ''
      }
    },
    /** 保存配置 **/
    save() {
      let that = this
      if(this.ruleConfigs==null || this.ruleConfigs.length<=0){
        /** 添加查询规则 **/
        this.addRuleItem();
        this.msgError("请维护，有效的查询规则");
        return false;
      }
      if(this.strIsEmpty(this.ruleId)){
        this.$prompt('请输入查询名称', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue:'查询'+new Date().toISOString()
        }).then(({ value }) => {
          //规则名称
          that.ruleName = value;
          that.reqSave();
        })
      }else{
        that.reqSave();
      }
    },
    /** 请求保存配置 **/
    reqSave() {
      let data ={
        buildKey:this.tabGenId,
        id:this.ruleId,
        ruleName:this.ruleName,
        ruleType:this.ruleType,
        ruleConfigs: JSON.stringify(this.ruleConfigs)
      }
      let that =this
      request({
        url: 'generator/superQuery/save',
        method: 'post',
        data: data
      }).then(res => {
        if (res.code == 200) {
          that.msgSuccess(res.msg)
          /** 获取配置信息 **/
          that.getSetInfo()
          /** 重置查询规则 **/
          that.resetRules()
        } else {
          that.msgError(res.msg)
        }
      })
    },
    /** 获取配置信息 **/
    getSetInfo() {
      if (this.strIsEmpty(this.tabGenId)) {
        return;
      }
      let that =this
      request({
        url: 'generator/superQuery/list/'+this.tabGenId,
        method: 'get'
      }).then(res => {
        if (res.code == 200) {
          that.savedRuleConfigs = res.data
        } else {
          that.msgError(res.msg)
        }
      })
    },
    /** 删除配置信息 **/
    removeSetInfo(row) {
      let that =this
      request({
        url: 'generator/superQuery/'+row['id'],
        method: 'delete'
      }).then(res => {
        if (res.code == 200) {
          that.msgSuccess(res.msg)
          setTimeout(() => {
            /** 重置查询规则 **/
            that.resetRules()
            /** 获取配置信息 **/
            that.getSetInfo()
          }, 1000)
        } else {
          that.msgError(res.msg)
        }
      })
    },
    /** 获取点击已保存规则，展示详情配置信息 **/
    handleRuleClick(rule){
      this.tabGenId = rule['buildKey']
      this.ruleId = rule['id']
      this.ruleName = rule['ruleName']
      this.ruleType = rule['ruleType']
      this.ruleConfigs = JSON.parse(rule['ruleConfigs'])
    },
    /**
     * 关闭
     */
    close() {
      this.$emit("close")
    },
    openModeForm() {
      this.openDialog=true;
    },
    closeDialog(){
      this.openDialog=false;
    },
    submitSet(){
      this.$set(this.modeConfig,'formWidth',this.$store.state.settings.formWidth);
      this.$set(this.modeConfig,'formHeight',this.$store.state.settings.formHeight);
      this.closeDialog();
    }
  },
};
</script>

<style scoped>

.btn-box {
  display: flex;
  align-items: center;
  justify-content: right;
}

.content-box {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
}

.content-box .content-title {
  background-color: #304156;
  color: white;
  width: 100%;
  padding: 10px;
}

.content-box .content-title span {
  margin-left: 6px;
}

/*基本信息*/
.content-box .content-item-box {
  width: 100%;
  display: flex;
  align-items: flex-start;
  padding: 10px 20px;
  flex-direction: column;
}

.content-box .content-item-box .title-box {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #e1e1e1;
}

.content-box .content-item-box .title-box .btn-item:hover {
  cursor: pointer;
}

.content-box .content-item-box .title-box .icon {
  margin-left: 4px;
}

.content-box .content-item-box .contents .icon {
  margin-left: 8px;
}

.content-box .content-item-box .contents .icon:hover {
  cursor: pointer;
}

.content-box .content-item-box .title-box .item-title {
  font-weight: bold;
}

.content-box .content-item-box .himt {
  font-size: 12px;
  color: #bfbfbf;
  margin-right: 4px;
}

.content-box .content-item-box .contents .himt {
  margin: 10px 0;
}

.content-box .content-item-box .contents {
  width: 100%;
  margin-bottom: 20px;
}

.content-box .content-item-box .contents .item-row {
  margin: 10px 0;
}
.item-row-content{
  display: flex;
  align-items: center;
}

.content-box .content-item-box .contents .item-row-box {
  display: flex;
  align-items: center;
  justify-content: center;
}

.content-box .content-item-box .contents .item-row-box .rule-number {
  color: #11A983;
  font-size: 12px;
}

.content-box .content-item-box .contents .item-row-box .el-form-item {
  width: 90%;
  margin: 0;
}

.contents .rule-type-box{
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 15px 0;
}

.content-box .content-item-box .contents .item-row-box .el-input,
.content-box .content-item-box .contents .item-row-box .el-select {
  margin: 0 5px;
}

.del-column{
  font-size: 14px;
}
.del-column:hover{
  cursor: pointer;
}

</style>
